const express = require("express");
const router = express.Router();
const fs = require("fs").promises;
const path = require("path");

const dataFilePath = path.join(__dirname, "./httpStudy.json");

// GET /api/harmonyOS/httpStudy
router.get("/", async (req, res) => {
    try {
        const fileContent = await fs.readFile(dataFilePath, "utf8");
        const data = {
            code: 200,
            result: JSON.parse(fileContent),
        };
        res.json(data);
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
});

// POST /api/harmonyOS/httpStudy
router.post("/", async (req, res) => {
    const { title, content } = req.body;
    try {
        const fileContent = await fs.readFile(dataFilePath, "utf8");
        const data = JSON.parse(fileContent);
        const newId = data.data.length > 0 ? Math.max(...data.data.map((item) => item.id)) + 1 : 1;
        const newItem = { id: newId, title, content };
        data.data.push(newItem);
        await fs.writeFile(dataFilePath, JSON.stringify(data, null, 2));
        res.status(201).json(newItem);
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
});

module.exports = router;
